package com.example.factory.api.facade.impl;

import com.example.factory.api.dto.DtoEquipment;
import com.example.factory.api.dto.PageResponse;
import com.example.factory.api.dto.Response;
import com.example.factory.api.dto.assembler.EquipmentAssembler;
import com.example.factory.api.dto.form.DtoEquipmentForm;
import com.example.factory.api.dto.form.DtoQueryEquipmentListForm;
import com.example.factory.api.facade.EquipmentFacade;
import com.example.factory.core.domain.Equipment;
import com.example.factory.core.repository.EquipmentRepository;
import com.example.factory.core.service.EquipmentService;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lei Tao
 */
@Service
public class EquipmentFacadeImpl implements EquipmentFacade {

    private final EquipmentAssembler equipmentAssembler;
    private final EquipmentRepository equipmentRepository;
    private final EquipmentService equipmentService;

    public EquipmentFacadeImpl(EquipmentAssembler equipmentAssembler, EquipmentRepository equipmentRepository, EquipmentService equipmentService) {
        this.equipmentAssembler = equipmentAssembler;
        this.equipmentRepository = equipmentRepository;
        this.equipmentService = equipmentService;
    }

    @Override
    public Response<List<DtoEquipment>> retrieveEquipments(DtoQueryEquipmentListForm dtoQueryEquipmentListForm) {
        Page<Equipment> equipments = equipmentRepository.findEquipments(dtoQueryEquipmentListForm);
        List<DtoEquipment> dtoQueryEquals = equipmentAssembler.toDtoEquipments(equipments);
        int totalPages = equipments.getTotalPages();
        long totalElements = equipments.getTotalElements();
        return PageResponse.success(totalElements, totalPages, dtoQueryEquals);
    }

    @Override
    public Response<DtoEquipment> retrieveEquipment(String guid) {
        Equipment equipment = equipmentRepository.findByGuidAndArchivedFalse(guid);
        DtoEquipment dtoEquipment = equipmentAssembler.toDtoEquipment(equipment);
        return Response.success(dtoEquipment);
    }

    @Override
    public Response<Void> deleteEquipment(String guid) {
        Equipment equipment = equipmentRepository.findByGuidAndArchivedFalse(guid);
        if (equipment == null){
            return Response.failed(3001);
        }
        equipmentService.deleteEquipment(equipment);
        return Response.success();
    }

    @Override
    public Response<DtoEquipment> saveOrUpdate(DtoEquipmentForm dtoEquipmentForm) {
       Equipment equipment = equipmentAssembler.toEquipment(dtoEquipmentForm);
       equipmentService.save(equipment);
        DtoEquipment dtoEquipment = equipmentAssembler.toDtoEquipment(equipment);
        return Response.success(dtoEquipment);
    }
}

